"use strict";

const { ApiController } = require("jax");

class AdminMenuController extends ApiController {
  get Model() {
    return this.ctx.model.AdminMenu;
  }

  // 必填字段
  get required() {
    return ["menuName"];
  }

  // 可提交字段
  get include() {
    return [
      ...this.required,
      "type",
      "icon",
      "rank",
      "isOpen",
      "isHide",
      "paht",
      "parentId",
      "authKey",
      "rank",
      "path",
      "apis",
    ];
  }

  // 返回JSON字段
  get json() {
    return [...this.include, "id", "index", "children"];
  }

  // 分类树
  async tree() {
    const { ctx } = this;
    const { helper } = ctx;
    const filter = this.getFilter();

    const tree = await this.Model.tree({
      filter,
      sort: {
        isTop: "DESC",
        rank: "ASC",
      },
    });

    helper.tree.eachTree(tree, (item) => this.toJson(item));

    ctx.body = {
      code: 0,
      msg: "success",
      data: tree,
    };
  }

  // 分类列表
  async index() {
    const { ctx } = this;
    const filter = this.getFilter();

    const returnData = await this.Model.flatTree({
      filter,
      sort: {
        isTop: "DESC",
        rank: "ASC",
      },
    });

    ctx.body = {
      code: 0,
      msg: "success",
      data: returnData.map((item) => this.toJson(item)),
    };
  }

  // 获取查询条件
  getFilter() {
    const { ctx } = this;
    const { query, helper } = ctx;
    const { admin } = ctx.state;
    const filter = {};

    // 菜单权限菜单
    if (query.action == "role_auth_menu") {
      if (this.isSuperAdmin) {
        query.systemType = query.systemType || admin.systemType;
      } else {
        query.systemType = admin.systemType;
      }
    }

    // 匹配搜索
    ["isOpen", "systemType"].map((key) => {
      if (query[key] && !query[key] == "") filter[key] = query[key];
    });

    return filter;
  }

  // 保存前
  async beforeSave() {
    const { ctx } = this;
    const { body } = ctx.request;

    if (body.parentId && body.parentId == body.id) throw "所选分类不能是自己";
  }

  // 保存后
  async afterSave() {
    this.service.systemUser.updateCache();
  }

  // 菜单路由
  async route() {
    const { ctx } = this;
    const { helper, state } = ctx;
    const { admin } = state;

    const adminRole = await ctx.model.AdminRole.findOne({
      _id: admin.roleId,
    });

    const filter = {
      isOpen: true,
      isHide: false,
      type: 0,
      systemType: adminRole.systemType,
    };

    // 指定菜单
    // if (!adminRole.isAdmin) filter._id = adminRole.menuIds

    // 非超级管理员，指定菜单
    // if (!adminRole.isSuperAdmin) filter._id = adminRole.menuIds

    // 指定菜单
    if (!adminRole.isAdmin)
      filter._id = [
        ...adminRole.halfMenuIds, // 半选菜单
        ...adminRole.menuIds, // 已选菜单
      ];

    const tree = await ctx.model.AdminMenu.tree({
      filter: filter,
      sort: {
        isTop: "Desc",
        rank: "ASC",
      },
    });

    helper.tree.eachTree(tree, (item) => this.toJson(item));

    ctx.body = {
      code: 0,
      msg: "success",
      data: tree,
    };
  }
}

module.exports = AdminMenuController;

/**
   * @api {POST} /system/menu [菜单] 新增
   * @apiUse AdminCommon
   * @apiGroup Menu
   * 
   * @apiBody {String} menuName 菜单名称
   * @apiBody {String} [parentId] 上级菜单
   * @apiBody {String} [path] 页面路径
   * @apiBody {String} [authKey] 权限标识（前端根据此标识显示或隐藏功能）
   * @apiBody {Number} [type=0] 0、页面 1、按钮
   * @apiBody {Boolean} [isOpen=false] 是否启用
   * @apiBody {Boolean} [isHide=false] 是否隐藏
   * @apiBody {String} [rank] 排序(从小到大)
   *
   * @apiSuccessExample {json} Success-Response:
  {
      "code": 0,
      "msg": "操作成功"
  }
*/

/**
   * @api {PUT} /system/menu/:id [菜单] 修改
   * @apiUse AdminCommon
   * @apiGroup Menu
   * 
   * @apiBody {String} [menuName] 菜单名称
   * @apiBody {String} [parentId] 上级菜单
   * @apiBody {String} [path] 页面路径
   * @apiBody {String} [authKey] 权限标识（前端根据此标识显示或隐藏功能）
   * @apiBody {Number} [type=0] 0、页面 1、按钮
   * @apiBody {Boolean} [isOpen=false] 是否启用
   * @apiBody {Boolean} [isHide=false] 是否隐藏
   * @apiBody {String} [rank] 排序(从小到大)
   *
   * @apiSuccessExample {json} Success-Response:
  {
      "code": 0,
      "msg": "操作成功"
  }
  */
/**
   * @api {GET} /system/menu/tree [菜单] 列表
   * @apiUse AdminCommon
   * @apiGroup Menu
   *
   * @apiSuccessExample {json} Success-Response:
{
    "code": 0,
    "msg": "success",
    "data": [
        {
            "isOpen": true,
            "menuName": "系统管理",
            "icon": "fa fa-cog",
            "id": "63fdfc35896a361078819dc4",
            "children": [
                {
                    "isHide": false,// 隐藏
                    "isOpen": false,// 菜单状态
                    "menuName": "菜单管理", // 菜单名称
                    "path": "/home", // 前端路径
                    "type": 0, // 类型 0、页面 1、按钮
                    "parentId": "63fdfc35896a361078819dc4", // 父菜单
                    "rank": 99,
                    "id": "63fdfc35896a361078819dc6",
                    "children": []
                },
            ]
        }
    ]
}
*/
/**
   * @api {GET} /system/menu/:id [菜单] 详情
   * @apiUse AdminCommon
   * @apiGroup Menu
   *
   * @apiSuccessExample {json} Success-Response:
  {
      "code": 0,
      "msg": "success",
      "data": {
        "isHide": false,// 隐藏
        "isOpen": false,// 菜单状态
        "menuName": "菜单管理", // 菜单名称
        "path": "/home", // 前端路径
        "type": 0, // 类型 0、页面 1、按钮
        "parentId": "63fdfc35896a361078819dc4", // 父菜单
        "rank": 99,
        "id": "63fdfc35896a361078819dc6",
      }
  }
*/

/**
   * @api {DELETE} /system/menu/:id [菜单] 删除
   * @apiUse AdminCommon
   * @apiGroup Menu
   *
   * @apiSuccessExample {json} Success-Response:
  {
      "code": 0,
      "msg": "操作成功"
  }
*/

/**
   * @api {GET} /system/menu/route [菜单] 路由
   * @apiUse AdminCommon
   * @apiGroup Menu
   *
   * @apiSuccessExample {json} Success-Response:
{
    "code": 0,
    "msg": "success",
    "data": [
        {
            "isOpen": true,
            "menuName": "系统管理",
            "icon": "fa fa-cog",
            "id": "63fdfc35896a361078819dc4",
            "children": [
                {
                    "isHide": false,// 隐藏
                    "isOpen": false,// 菜单状态
                    "menuName": "菜单管理", // 菜单名称
                    "path": "/home", // 前端路径
                    "type": 0, // 类型 0、页面 1、按钮
                    "parentId": "63fdfc35896a361078819dc4", // 父菜单
                    "rank": 99,
                    "id": "63fdfc35896a361078819dc6",
                    "children": []
                },
            ]
        }
    ]
  }
*/
